<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <Card class="r-n-fs-c">
      <Select style="width: 240px;" v-model="page.projectId" @on-change="searchDanger" clearable placeholder="所属项目">
        <Option v-for="item in projectList" :key="item.id" :value="item.id">{{item.projectName}}</Option>
      </Select>
      <Select style="width: 240px;margin-left: 5px;" v-model="page.status" @on-change="searchDanger" clearable placeholder="状态">
        <Option :value=1>待处理</Option>
        <Option :value=2>已完成</Option>
      </Select>
      <Select style="width: 240px;margin-left: 5px;" v-model="searchKey" clearable @on-clear="searchKeyClear" placeholder="精确匹配查询参数">
        <Option v-for="item in searchParamList" :key="item.key" :value="item.key">{{item.show}}</Option>
      </Select>
      <Input v-model="searchValue" placeholder="请输入查询内容..." clearable style="width: 300px;margin-left: 5px;" />
      <Button @click="selectPageList(page)" type="primary" style="width: 100px;margin-left: 5px;">查询</Button>
    </Card>
    <Divider/>
    <div>
      <Table id="card-list-info-table" class="table" stripe
             border
             show-header
             highlight-row
             :loading="isLoading"
             :columns="tableColumns"
             :data="dataList">
      </Table>
      <Divider/>
      <Card style="margin-bottom: 15px;">
        <Page class="r-w-c-c"
              style="width: 100%"
              class-name="card-list-info-page"
              :total="page.total"
              :current="page.pageNum"
              :page-size="page.pageSize"
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange"
              show-elevator
              show-sizer
              show-total/>
      </Card>
    </div>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";
import moment from "moment";
import {Request} from "@/global/config";

export default {
  name: "Danger",
  computed: {
    ...mapState(["url", "host", "resourceHost", "realSideWidth","projectList"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      //精准搜索查询字段
      searchKey: 'id',
      //精准搜索查询字段
      searchValue: null,
      //数据是否在加载中
      isLoading: false,
      //确认框是否显示
      modalTip: false,
      //确认框展示内容
      modalTipContent: null,
      //弹出确认操作加载中
      modalLoading: false,
      //是否在更改单页数量
      isPageSizeChanging: false,
      //当前弹出框标题
      modalTitle: '',
      //弹出框标题集合
      operatorType: ['禁用险情','解禁险情','删除险情'],
      //操作参数集合
      selectForm: {
        id: null,
        status: null,
        remarks: null,
        dangerTypeId: null,
        dangerLevelId: null,
        flyTaskId: null,
        projectId: null
      },
      //分页查询参数
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id',
        id: null,
        status: null,
        dangerTypeId: null,
        dangerLevelId: null,
        flyTaskId: null,
        projectId: null
      },
      //表格结构
      tableColumns: [
        {
          title: '险情ID',
          key: 'id',
          width: 100,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '位置',
          resizable: true,
          minWidth: 240,
          align: "center",
          render: function (createElement,data){
            let {lng,lat } = data.row;
            return createElement('span','['+lng+','+lat+']');
          }
        },
        {
          title: '险情标记图片',
          key: 'labelImage',
          resizable: true,
          width: 150,
          minWidth: 100,
          align: "center",
          render:this.imageRender,
        },
        {
          title: '备注',
          key: 'remarks',
          resizable: true,
          width: 180,
          minWidth: 150,
          align: "center"
        },
        {
          title: '险情类型',
          key: 'dangerTypeId',
          resizable: true,
          minWidth: 120,
          align: "center",
          render:this.dangerTypeNameRender
        },
        {
          title: '险情等级',
          key: 'dangerLevelId',
          resizable: true,
          minWidth: 180,
          align: "center",
          render:function (createElement,data) {
            let {dangerLevelId} = data.row;
            let level;
            if (dangerLevelId === 1){
              level = '一级';
            }else if (dangerLevelId === 2) {
              level = '二级'
            }else if (dangerLevelId === 3) {
              level = '三级'
            }
            return createElement('span',level);
          }
        },
        {
          title: '险情状态',
          resizable: true,
          width: 130,
          align: "center",
          render: function(createElement, data) {
            let {status} = data.row;
            if (status === 0) {
              return createElement('span','未指派');
            }
            if (status === 1) {
              return createElement('span','处理中');
            }
            if (status === 2) {
              return createElement('span','已解决');
            }
          },
        },
        {
          title: '标记时间',
          resizable: true,
          width: 180,
          align: "center",
          render: function (createElement, data) {
            let {createTime} = data.row;
            return createElement('span',moment.unix(createTime/1000).format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        {
          title: '所属任务ID',
          key: 'flyTaskId',
          resizable: true,
          width: 180,
          align: "center"
        },
        {
          title: '所属项目',
          key: 'projectId',
          resizable: true,
          width: 180,
          align: "center",
          fixed: "right",
          render: Request.projectNameRender
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 150,
          align: "center",
          fixed: "right",
          render: this.operatorRenderFunction
        }
      ],
      //表格数据
      dataList: [],
      //险情类型Map
      dangerTypeMap: new Map(),
      //搜索参数
      searchParamList: [
        {
          key: 'id',
          show: "险情ID",
        },
        {
          key: "flyTaskId",
          show: "所属任务ID",
        }
      ]
    }
  },
  mounted: function () {
    let self = this;
    //等待获取完所有项目，所有险情类型后初始化获取险情列表数据
    axios.all([self.selectDangerTypeList()]).then(self.axios.spread( (dangerTypeRsp) => {
      //获取险情类型结果处理
      if (dangerTypeRsp.data.state === 200){
        let {records} = dangerTypeRsp.data.content;
        for (let level of records) {
          self.dangerTypeMap.set(level['id'],level['typeName']);
        }
      }
      //同步获取险情列表
      self.selectPageList(self.page);
    }));
  },
  methods: {

    /**
     * 根据参数精确搜索险情
     */
    searchDanger(){
      this.page.pageNum = 1;
      this.selectPageList(this.page);
    },

    /**
     * 参数值清除
     */
    searchKeyClear(){
      let self = this;
      self.searchValue = null;
    },

    /**
     * 图片渲染
     * @param createElement
     * @param data
     * @return {*}
     */
    imageRender(createElement, data){
      let {labelImage} = data.row,self = this;
      return createElement('img', {
        style: {
          height: '25px',
          cursor: 'pointer'
        },
        attrs: {
          title: '点击查看大图',
          src: labelImage
        },
        on: {
          click: function () {
            self.$store.state.imageWindowUrl = labelImage;
            self.$store.state.isImageWindowShow = true;
          }
        }
      });
    },

    /**
     * 险情类型名称渲染
     * @param createElement
     * @param data
     * @return {*}
     */
    dangerTypeNameRender(createElement, data) {
      let {dangerTypeId} = data.row,self = this;
      return createElement('span',self.dangerTypeMap.get(dangerTypeId));
    },

    /**
     * 页数更改
     * @param changedPage
     */
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },

    /**
     * 单页数量更改
     * @param changedPageSize
     */
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },

    /**
     * 删除险情确认提示框
     */
    modalTipOk() {
      this.modalLoading = true;
      switch (this.modalTitle){
        case this.operatorType[2]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.deleteDanger(this.selectForm.id);
        }break;
      }
    },

    /**
     * 操作渲染
     * @param createElement
     * @param data
     * @return {*}
     */
    operatorRenderFunction(createElement, data) {
      let self = this;
      let { id } = data.row;
      let btnList = [];
      btnList.push(createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#FF6666'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.selectForm.id = id;
            self.modalTitle = self.operatorType[2];
            self.modalTipContent = '将要永久删除该险情，是否继续 ? ';
            self.modalTip = true;
          }
        },
      }, '删除'));
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },

    /**
     * 分页获取险情
     * @param selectForm
     */
    selectPageList(selectForm) {
      let self = this;
      let form = Object.assign({}, selectForm);
      if (self.searchKey !== null && self.searchValue !== null && self.searchValue !== ""){
        form[self.searchKey] = self.searchValue.trim();
      }
      self.dataList = [];
      self.isLoading = true;
      axios.get(self.url.danger_list, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    },

    /**
     * 获取所有险情类型
     * @return {Promise<AxiosResponse<any>>}
     */
    selectDangerTypeList() {
      let self = this;
      return axios.get(self.url.danger_type_list, {params: {pageSize:-1,descParams:''}});
    },

    /**
     * 删除险情
     * @param dangerId
     */
    deleteDanger(dangerId){
      let self = this;
      axios.delete(self.url.danger_delete + dangerId).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.$Message.success(message);
          self.selectPageList(self.page);
          self.$Spin.hide();
        }
      })
    }
  }
}
</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
}

.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}

.item-input-span {
  /*height: inherit;*/
  width: 120px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>